package com.voygern.task1.dao;

import java.io.IOException;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.voygern.task1.dao.mapper.UserDaoMapper;
import com.voygern.task1.model.User;
@Component
public class UserDao implements UserDaoMapper{
	@Autowired
	private DBAccess access;
	private SqlSession session;
	public List<User> queryAll() {
		try {
			session = access.getSession();
			List<User> users = session.getMapper(UserDaoMapper.class).queryAll();
			return users;
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(session!=null)
			{
				session.close();
				session=null;
			}
		}
		return null;
	}
	public int add(User user) {
		try {
			session = access.getSession();
			return session.getMapper(UserDaoMapper.class).add(user);
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			disposeSession();
		}
		return -1;
	}
	public int deleteUserById(long id) {
		try {
			session = access.getSession();
			return session.getMapper(UserDaoMapper.class).deleteUserById(id);
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			disposeSession();
		}
		return -1;
	}
	public int changeUpdateAtByUsername(String name, long update_at) {
		try {
			session = access.getSession();
			return session.getMapper(UserDaoMapper.class).changeUpdateAtByUsername(name, update_at);
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			disposeSession();
		}
		return -1;
	}

	public User queryUserById(int id) {
		try {
			session = access.getSession();
			return session.getMapper(UserDaoMapper.class).queryUserById(id);
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			disposeSession();
		}
		return null;
	}
	
	private void disposeSession()
	{
		if(session!=null)
		{
			session.close();
			session=null;
		}
	}
	public void setAccess(DBAccess access)
	{
		this.access = access;
	}
}
